/*数据管理模块*/

#pragma once

#include <iostream>
#include <mutex>
#include <cassert>
#include <cstdio>

#include "util.hpp"
using namespace ns_util;

class user_table
{
private:
    MYSQL *_mysql;     // mysql操作句柄
    std::mutex _mutex; // 互斥锁保护数据库的访问操作
public:
    user_table(const std::string &host,
               const std::string &user,
               const std::string &passwd,
               const std::string &db_name,
               uint16_t port = 3306)
    {
        _mysql = mysql_util::mysql_create(host, user, passwd, db_name, port);
        assert(_mysql != nullptr);
    }

    ~user_table()
    {
        mysql_util::mysql_destory(_mysql);
        _mysql = nullptr;
    }

    // 注册时新增⽤⼾
    bool insert(Json::Value &user)
    {
#define INSERT_USER "insert user values(null, '%s', MD5('%s'), 1000, 0, 0);"

        if (user["password"].isNull() || user["username"].isNull())
        {
            LOG(INFO) << "INPUT PASSWORD OR USERNAME" << "\n";
            return false;
        }
        if (select_by_name(user["username"].asString(), user) == true)
        {
            LOG(ERROR) << "username is exists!!" << "\n";
            return false;
        }
        char sql[4096] = {0};
        sprintf(sql, INSERT_USER, user["username"].asCString(), user["password"].asCString());
        bool ret = mysql_util::mysql_exec(_mysql, sql);
        if (ret == false)
        {
            LOG(ERROR) << "insert user info failed!!\n";
            return false;
        }
        return true;
    }

    // 登录验证，并返回详细的⽤⼾信息
    bool login(Json::Value &user)
    {
        if (user["password"].isNull() || user["username"].isNull())
        {
            LOG(INFO) << "INPUT PASSWORD OR USERNAME" << "\n";
            return false;
        }
#define LOGIN_USER "select id, score, total_count, win_count from user where username='%s' and password=MD5('%s');"
        char sql[4096] = {0};
        sprintf(sql, LOGIN_USER, user["username"].asCString(), user["password"].asCString());
        MYSQL_RES *res = nullptr;
        {
            std::unique_lock<std::mutex> lock(_mutex);
            bool ret = mysql_util::mysql_exec(_mysql, sql);
            if (ret == false)
            {
                LOG(ERROR) << "user login failed!!\n";
                return false;
            }
            // 按理说要么有数据，要么没有数据，就算有数据也只能有⼀条数据
            res = mysql_store_result(_mysql);
            if (res == nullptr)
            {
                LOG(ERROR) << "have no login user info!!" << "\n";
                return false;
            }
        }

        int row_num = mysql_num_rows(res);
        if (row_num != 1)
        {
            LOG(ERROR) << "the user information queried is not unique!!" << "\n";
            return false;
        }
        MYSQL_ROW row = mysql_fetch_row(res);
        user["id"] = (Json::UInt64)std::stol(row[0]);
        user["score"] = (Json::UInt64)std::stol(row[1]);
        user["total_count"] = std::stoi(row[2]);
        user["win_count"] = std::stoi(row[3]);
        mysql_free_result(res);
        return true;
    }

    // 通过⽤⼾名获取⽤⼾信息
    bool select_by_name(const std::string &name, Json::Value &user)
    {
#define USER_BY_NAME "select id, score, total_count, win_count from user where username='%s';"
        char sql[4096] = {0};
        sprintf(sql, USER_BY_NAME, user["username"].asCString());
        MYSQL_RES *res = NULL;
        {
            std::unique_lock<std::mutex> lock(_mutex);
            bool ret = mysql_util::mysql_exec(_mysql, sql);
            if (ret == false)
            {
                LOG(ERROR) << "get user by name failed!!\n";
                return false;
            }
            // 按理说要么有数据，要么没有数据，就算有数据也只能有⼀条数据
            res = mysql_store_result(_mysql);
            if (res == NULL)
            {
                LOG(ERROR) << "have no user info!!" << "\n";
                return false;
            }
        }

        int row_num = mysql_num_rows(res);
        // std::cout << row_num << "\n";
        if (row_num == 0)
        {
            LOG(ERROR) << "have no user info!!" << "\n";
            mysql_free_result(res);
            return false;
        }
        if (row_num != 1)
        {
            LOG(ERROR) << "the user information queried is not unique!!" << "\n";
            return false;
        }
        MYSQL_ROW row = mysql_fetch_row(res);
        user["id"] = (Json::UInt64)std::stol(row[0]);
        user["username"] = name;
        user["score"] = (Json::UInt64)std::stol(row[1]);
        user["total_count"] = std::stoi(row[2]);
        user["win_count"] = std::stoi(row[3]);
        mysql_free_result(res);
        return true;
    }

    // 通过⽤⼾名id获取⽤⼾信息
    bool select_by_id(uint64_t id, Json::Value &user)
    {
#define USER_BY_ID "select username, score, total_count, win_count from user where id=%ld;"
        char sql[4096] = {0};
        sprintf(sql, USER_BY_ID, id);
        MYSQL_RES *res = nullptr;
        {
            std::unique_lock<std::mutex> lock(_mutex);
            bool ret = mysql_util::mysql_exec(_mysql, sql);
            if (ret == false)
            {
                LOG(ERROR) << "get user by id failed!!\n";
                return false;
            }
            // 按理说要么有数据，要么没有数据，就算有数据也只能有⼀条数据
            res = mysql_store_result(_mysql);
            if (res == nullptr)
            {
                LOG(ERROR) << "have no user info!!" << "\n";
                return false;
            }
        }

        int row_num = mysql_num_rows(res);
        if (row_num == 0)
        {
            LOG(ERROR) << "have no user info!!" << "\n";
            mysql_free_result(res);
            return false;
        }
        if (row_num != 1)
        {
            LOG(ERROR) << "the user information queried is not unique!!" << "\n";
            return false;
        }
        MYSQL_ROW row = mysql_fetch_row(res);
        user["id"] = (Json::UInt64)id;
        user["username"] = row[0];
        user["score"] = (Json::UInt64)std::stol(row[1]);
        user["total_count"] = std::stoi(row[2]);
        user["win_count"] = std::stoi(row[3]);
        mysql_free_result(res);
        return true;
    }

    // 胜利时天梯分数增加30分，战⽃场次增加1，胜利场次增加1
    bool win(uint64_t id)
    {
#define USER_WIN "update user set score=score+30, total_count=total_count+1, win_count=win_count+1 where id=%ld;"
        char sql[4096] = {0};
        sprintf(sql, USER_WIN, id);
        bool ret = mysql_util::mysql_exec(_mysql, sql);
        if (ret == false)
        {
            LOG(ERROR) << "update win user info failed!!\n";
            return false;
        }
        return true;
    }

    // 失败时天梯分数减少30，战⽃场次增加1，其他不变
    bool lose(uint64_t id)
    {
#define USER_LOSE "update user set score=score-30, total_count=total_count+1 where id=%ld;"
        char sql[4096] = {0};
        sprintf(sql, USER_LOSE, id);
        bool ret = mysql_util::mysql_exec(_mysql, sql);
        if (ret == false)
        {
            LOG(ERROR) << "update lose user info failed!!\n";
            return false;
        }
        return true;
    }
};
